package com.fmistuff.chain.nodes;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;


public abstract class MarkovNode implements INode {
	protected static final Random RANDOM = new Random(System.nanoTime());
	protected static final String recursiveKey = "RecursiveKey";
	protected static final String EMPTY = "";
	
	private String data;
	private float probability;
	
	public MarkovNode(String data){
		this(data, 0.5f);
	}
	
	public MarkovNode(String data, float probability){
		this.setData(data);
		this.setProbability(probability);
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
	public float getProbability() {
		return probability;
	}
	public void setProbability(float probability) {
		this.probability = probability;
	}
	
	
	public boolean isFinal(){
		//force recursion wehen dumbass mistakes appear
		return false;
	}
	
	public static MarkovNode pickANode(Map<String, MarkovNode> pool) {
		//first check sum of all entries
		float sum = 0;
		for (Entry<String, MarkovNode> nodeEntry : pool.entrySet()){
			sum+=nodeEntry.getValue().getProbability();
		}
		
		//then pick a random number
		float randomNum = (RANDOM.nextFloat()*sum); //scale random rom 1 to sum
		Iterator<MarkovNode> iterator = pool.values().iterator();
		MarkovNode currentNode = null;

		//and get the first entry that gets the checksum higher than the random number
		for (float checkSum = 0; checkSum < randomNum && iterator.hasNext();) {
			currentNode = iterator.next();
			checkSum += currentNode.getProbability();
		}
		return currentNode;
	}
	
	public abstract String descend();
}
